<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { getClassifyApi, getHomeBannerApi, getRandomWallApi, getWallNewsListApi } from '@/api/index'
import CustomNavBar from '@/components/CustomNavBar.vue'
import MenuHeader from '@/pages/index/components/MenuHeader.vue'
import { useWallStore } from '@/store'
import { timeAgo } from '@/utils/utils'

defineOptions({
  name: 'Home',
  components: { CustomNavBar, MenuHeader },
})
definePage({
  // 使用 type: "home" 属性设置首页，其他页面不需要设置，默认为page
  type: 'home',
  style: {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
})
let { classListTotal, classList } = storeToRefs(useWallStore())
let bannerList = reactive([])
let scrollText = reactive([])
let classify = reactive([])
let classifyParams = reactive({
  pageNum: 1,
  pageSize: 9,

})
let randomWall = ref([])
let wallNewsList = reactive([])
let bannerLoading = ref(true)

function getHomeBanner() {
  getHomeBannerApi().then((res) => {
    bannerList.push(...res)
  }).finally(() => {
    bannerLoading.value = false
  })
}
function getClassify() {
  classify.length >= classifyParams.pageSize && (classifyParams.pageNum = Math.ceil(classify.length / classifyParams.pageSize) + 1)
  getClassifyApi(classifyParams).then((res) => {
    classify.push(...res)
  })
}
function getRandomWall() {
  getRandomWallApi().then((res) => {
    randomWall.value = res
    classListTotal.value = res.length
  })
}
function getWallNewsList() {
  getWallNewsListApi().then((res) => {
    wallNewsList.push({
      _id: 1,
      title: '萌宠壁纸-萌宠壁纸大集合',
      author: '萌宠壁纸接口',
      select: false,
    })
    wallNewsList.push(...res)
    scrollText.push(...wallNewsList.filter(item => !item.select).map(item => item.title))
  })
}

function goClassify() {
  uni.switchTab({
    url: '/pages/classification/classification',
  })
}
function noticeBarHandler(value) {
  console.log(wallNewsList, 'wallNewsList')

  if (value === 0) {
    uni.navigateTo({
      url: '/pages/pet/pet',
    })
  }
}
function goPreview(detail) {
  classList.value = randomWall.value
  classListTotal.value = randomWall.value.length
  console.log(detail._id, 111)

  uni.navigateTo({
    url: `/pages/preview/preview?id=${detail._id}`,
  })
}
function goClassList(item) {
  uni.navigateTo({
    url: `/pages/classList/classList?classid=${item._id}&classname=${item.name}`,
  })
}
function goClassListToBanner(e) {
  if (bannerList[e].target === 'self') {
    const [idPart, namePart] = bannerList[e].url.split('&')
    const _id = idPart.split('=')[1] // "6524a48f6523417a8a8b825d"
    const name = namePart.split('=')[1] // "可爱萌宠"
    let item = {
      _id,
      name,
    }
    goClassList(item)
  }
  else {
    wx.navigateToMiniProgram({
      appId: bannerList[e].appid, // 必填，目标小程序的唯一标识
      path: bannerList[e].picurl,
      extraData: {

      },
      success(res) {
        console.log('跳转成功', res)
      },
      fail(err) {
        console.error('跳转失败', err)
      },
    })
  }
}
onLoad(() => {
  getHomeBanner()
  getRandomWall()
  getClassify()
  getWallNewsList()
})
onUnload(() => {
  classList.value = []
  randomWall.value = []
})
// #ifndef H5
onShareAppMessage((e) => {
  // 分享给好友

  return {
    title: '花朵壁纸-好友',
    path: '/pages/index/index',
  }
})
// 分享朋友圈
onShareTimeline(() => {
  return {
    title: '花朵壁纸-朋友圈',
    imageUrl: '/static/images/flower.png', // 1比1
  }
})
// #endif

/**
 *
 */
// #endregion
</script>

<template>
  <view class="bg-white">
    <uv-row justify="space-center" custom-style="margin:10px">
      <uv-col span="12">
        <CustomNavBar title="推荐" />
        <!-- 轮播图 -->
        <uv-swiper
          v-if="bannerList.length > 0"
          :loading="bannerLoading" :list="bannerList" key-name="picurl" interval="2000" autoplay circular
          class="size-full h-230px" @click="goClassListToBanner"
        />
        <!-- 滚动条公告 -->
        <uv-notice-bar
          :text="scrollText" direction="column" mode="link" speed="250" bg-color="#eee" color="#498b45"
          class="my-10px c-#2a282c" @click="noticeBarHandler"
        />
        <!-- 今日推荐 -->
        <MenuHeader>
          <!-- 左侧标题 -->
          <template #left>
            <text class="text-22px text-gray-800 font-bold">每日推荐</text>
          </template>
          <!-- 右侧内容 -->
          <template #right>
            <view class="flex whitespace-nowrap">
              <uv-icon name="calendar" size="16" color="#498b45" />
              <view class="text-16px c-#498b45">
                <uni-dateformat :date="Date.now()" format="dd日" />
              </view>
            </view>
          </template>
        </MenuHeader>
        <scroll-view scroll-x show-scrollbar class="swiper-scroll-x">
          <view v-for="data in randomWall" :key="data._id" class="swiper-scroll-x-img" @click="goPreview(data)">
            <uv-image
              :src="data.smallPicurl" :observe-lazy-load="true" width="200px" height="330px" radius="4"
              key-name="smallPicurl"
            >
              <template #loading>
                <uv-loading-icon color="#57be6a" />
              </template>
            </uv-image>
          </view>
        </scroll-view>
        <!-- 专题精选 -->
        <MenuHeader>
          <!-- 左侧标题 -->
          <template #left>
            <text class="text-22px text-gray-800 font-bold">专题精选</text>
          </template>
          <!-- 右侧内容 -->
          <template #right>
            <view class="text-16px c-#498b45" @click="goClassify">
              More+
            </view>
          </template>
        </MenuHeader>
        <!-- 专题精选 宫格 -->
        <view class="relative grid grid-cols-3 gap-3">
          <view
            v-for="(item, index) in classify" :key="item._id"
            :class="{ 'last-grid-item': index === classify.length - 1 }"
            class="relative h-230px w-28vw overflow-hidden rounded-8px" @click="goClassList(item)"
          >
            <uv-image :src="item.picurl" width="28vw" height="330">
              <template #loading>
                <uv-loading-icon color="green" />
              </template>
            </uv-image>
            <view
              v-if="index === classify.length - 1"
              class="last-mark grid-box-overlay absolute bottom-0 h-230px w-28vw flex flex-col items-center justify-center rounded-8px bg-black bg-opacity-40"
              @click.stop="goClassify"
            >
              <uv-icon name="more-dot-fill" size="36" color="#ffffff" />
              <text class="text-16px text-white">更多</text>
            </view>
            <view v-else>
              <view
                class="last-mark grid-box-overlay absolute bottom-0 h-30px w-28vw flex items-center justify-center rounded-b-8px bg-black bg-opacity-40"
              >
                <text class="text-16px text-white">{{ item.name }}</text>
              </view>
              <view
                class="grid-box-overlay absolute top-0 flex items-center justify-center rounded-br-4px bg-#2fde72 bg-opacity-40 px-5px py-5px"
              >
                <text class="text-12px text-white">{{ timeAgo(item.updateTime) }}</text>
              </view>
            </view>
          </view>
        </view>
      </uv-col>
    </uv-row>
  </view>
</template>

<style lang="scss" scoped>
.swiper-scroll-x {
  white-space: nowrap;
  margin: 10px 0;

  .swiper-scroll-x-img {
    display: inline-block;
    margin-right: 10px;

    &:last-child {
      margin-right: 0;
    }
  }
}

.last-mark {
  /* 添加磨砂玻璃效果 */
  backdrop-filter: blur(10px);
  /* 模糊效果 */
  -webkit-backdrop-filter: blur(10px);
  /* Safari 兼容 */
  background-color: rgba(0, 0, 0, 0.3);
  /* 半透明背景 */
}
</style>
